package com.nuo.common.quartz.core.operate;


import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.nuo.common.quartz.core.entity.QuartzJobDO;
import com.nuo.common.quartz.core.entity.QuartzLogDO;
import com.nuo.common.quartz.core.enums.JobModeEnum;
import com.nuo.common.quartz.core.enums.LogStateEnum;
import com.nuo.common.quartz.core.service.QuartzLogService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.web.bind.annotation.RequestMethod;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.Locale;

/**
 * 任务记录
 *
 * @author LGC
 */
@Slf4j
public class QuartzRecord extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext context) {
        QuartzJobDO quartzJobDO = (QuartzJobDO) context.getMergedJobDataMap().get(QuartzJobDO.JOB_PARAM_KEY);
        log.info("执行job:{}", quartzJobDO);
        QuartzLogService quartzLogService = (QuartzLogService) SpringContextUtil.getBean("quartzLogService");
        Integer jobMode = quartzJobDO.getJobMode();
        String beanName = quartzJobDO.getBeanName();
        String params = quartzJobDO.getParams();
        // 定时器日志记录
        QuartzLogDO quartzLogDO = new QuartzLogDO();
        quartzLogDO.setJobId(quartzJobDO.getId());
        quartzLogDO.setJobMode(quartzJobDO.getJobMode());
        quartzLogDO.setBeanName(beanName);
        quartzLogDO.setParams(params);
        quartzLogDO.setCreateTime(new Date());
        long beginTime = System.currentTimeMillis();
        params = StrUtil.isBlank(params) ? "{}" : params;
        try {
            // 加载并执行
            if (jobMode.equals(JobModeEnum.BEAN.getKey())) {
                Object target = SpringContextUtil.getBean(beanName);
                Method method = target.getClass().getDeclaredMethod("run", String.class);
                method.invoke(target, params);
            }
            if (jobMode.equals(JobModeEnum.HTTP.getKey())) {
                String httpMethod = getHttpMethod(beanName);
                String httpUrl = getHttpUrl(beanName);
                if (RequestMethod.POST.name().equals(httpMethod)) {
                    HttpUtil.post(httpUrl, params);
                }
                if (RequestMethod.GET.name().equals(httpMethod)) {
                    HttpUtil.get(httpUrl, JSONUtil.parseObj(params));
                }
            }

            long executeTime = System.currentTimeMillis() - beginTime;
            quartzLogDO.setTimes((int) executeTime);
            quartzLogDO.setState(LogStateEnum.LOG_SUS.getStatus());
        } catch (Exception e) {
            log.error("执行任务异常：job:{}", quartzJobDO, e);
            // 异常信息
            long executeTime = System.currentTimeMillis() - beginTime;
            quartzLogDO.setTimes((int) executeTime);
            quartzLogDO.setState(LogStateEnum.LOG_FAIL.getStatus());
            quartzLogDO.setError(e.getMessage());
        } finally {
            quartzLogService.insert(quartzLogDO);
        }
    }

    private String getHttpMethod(String urlStr) {
        return urlStr.split(":")[0].toUpperCase(Locale.ROOT);
    }

    private String getHttpUrl(String urlStr) {
        return urlStr.substring(urlStr.split(":")[0].length() + 1);
    }


}
